package com.children.growth.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import jakarta.annotation.PostConstruct;
import java.io.File;

/**
 * 文件上传配置类
 * 
 * @author children
 * @since 1.0.0
 */
@Configuration
public class FileUploadConfig implements WebMvcConfigurer {

    @Value("${file.upload.path:uploads}")
    private String uploadPath;

    @PostConstruct
    public void init() {
        // 确保上传目录存在
        createUploadDirectories();
    }

    /**
     * 创建上传目录
     */
    private void createUploadDirectories() {
        try {
            // 创建主上传目录
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                boolean created = uploadDir.mkdirs();
                System.out.println("创建上传目录: " + uploadDir.getAbsolutePath() + " - " + (created ? "成功" : "失败"));
            }

            // 创建子目录
            String[] subDirs = {"drawings", "audio", "images"};
            for (String subDir : subDirs) {
                File subDirFile = new File(uploadPath + "/" + subDir);
                if (!subDirFile.exists()) {
                    boolean created = subDirFile.mkdirs();
                    System.out.println("创建子目录: " + subDirFile.getAbsolutePath() + " - " + (created ? "成功" : "失败"));
                }
            }
        } catch (Exception e) {
            System.err.println("创建上传目录失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 配置静态资源映射
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/uploads/**")
                .addResourceLocations("file:" + uploadPath + "/");
        
        System.out.println("配置静态资源映射: /uploads/** -> " + uploadPath + "/");
    }

    /**
     * 获取上传路径
     */
    public String getUploadPath() {
        return uploadPath;
    }
} 